import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Table, Button, Form, Input, Modal, Row, Col, Radio } from 'antd';
import { FormInstance } from 'antd/lib/form';
import PropTypes from 'prop-types';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import PateoTable from '@/components/common/PateoTable';
import styles from '@/components/common/PateoTable/TableList.less';
import ApplyModal from './applyModal';

// 0 待提交；1 审批通过；2 审批中；3 审批驳回
const statusData = {
  0: '待提交',
  1: '审批通过',
  2: '审批中',
  3: '审批驳回',
}
const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  knowledgeApply: state.knowledgeApply,
  loading: state.loading.models['knowledgeApply'],
});
class Apply extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  constructor(props: any) {
    super(props);
    let userAccount: any = '';
    try {
      userAccount = sessionStorage.getItem('accountName');
    } catch (e) {}
    this.state = {
      // selectOptions: [],
      formValues: {},
      userAccount: userAccount,  //  用户名
      userId: '', //  用户id
      
      extraArgs: {
        majorCodeList: [],
        status: ['0', '1','2','3'],
        sort: [{
          orderBy: "createTime", 
          direction: "desc"
        }],
        createBy: userAccount,
      },
      visible: false,
      sortOrder: 'descend', // ascend descend
      currentRecord: {},  //  当前查看的故障
      modalType: 'add',
      specialtyOption: [],  //  专业下拉选项
      type: '1',
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { userAccount } = this.state;

    dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/findSidByAccountName',
        accountName: userAccount || '',
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          this.setState({
            userId: res.data || ''
          })
        }
      }
    })
    //  获取当前用户专业信息
    dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/mscontent/knowledge/getPermissions',
        accountName: userAccount || '',
        current: 1,
        pageSize: 10,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          const { extraArgs: {majorCodeList, ...i}} = this.state;
          //  下拉框
          const tempList = this.formatSpecialtyOption(res?.data?.list);
          //  账号专业
          const tempMajorCodeList = tempList.map(item => item.value);
          //  必传参数
          const tempExtraArgs = {
            majorCodeList: tempMajorCodeList,
            ...i
          }
          this.setState({
            specialtyOption: tempList,
            extraArgs: tempExtraArgs,
          }, () => {
            dispatch({
              type: 'knowledgeApply/postFetchPage',
              payload: {
                url: '/mscontent/knowledge/apply/list',
                ...tempExtraArgs
              }
            });
          })
        }
      }
    })
  }

  //  专业下拉选项
  formatSpecialtyOption = (list: any[]) => {
    let tempList: any[] = [];
    if (list && list.length > 0) {
      const data = list[0];
      data.majorIds && data.majorIds.forEach((v: any, idx: number) => {
        tempList.push({
          value: data.majorCodes[idx] + '',
          label: data.majorNames[idx],
          id: v,
        })
      })
    }
    return tempList
  }

  handleQuery = () => {
    this.formRef.current?.submit();
  }

  onChange = (val: any) => {
    const { dispatch } = this.props;
    const { formValues, extraArgs: {status, ...i} } = this.state;
    const data = {
      1: [0,1,2,3],
      2: [0],
      3: [2],
      4: [1],
      5: [3],
    };

    this.setState({
      type: val,
      extraArgs: {
        status: data[val],
        ...i
      }
    }, () => {
      const { extraArgs } = this.state
      dispatch({
        type: 'knowledgeApply/postFetchPage',
        payload: {
          url: '/mscontent/knowledge/apply/list',
          ...extraArgs,
          ...formValues
        }
      });
    })
  }

  //  新增
  applyKnowledge = () => {
    this.setState({
      visible: true,
      modalType: 'add',
    })
  }

  //  关闭知识库编辑弹框
  closeModal = () => {
    this.setState({
      visible: false,
      modalType: 'add',
      currentRecord: {},
    })
    this.refreshPage();
  }

  refreshPage = () => {
    const { dispatch } = this.props;
    const { extraArgs, userAccount } = this.state;
    if (extraArgs.majorCodeList && extraArgs.majorCodeList.length > 0) {
      dispatch({
        type: 'knowledgeApply/postFetchPage',
        payload: {
          url: '/mscontent/knowledge/apply/list',
          ...extraArgs
        }
      });
    } else {
      dispatch({
        type: 'http/getDataWithRes',
        payload: { 
          url: '/mscontent/knowledge/getPermissions',
          accountName: userAccount || '',
          current: 1,
          pageSize: 10,
        },
        callback: (res: any) => {
          if (res.statusCode === '0') {
            const { extraArgs: {majorCodeList, ...i}} = this.state;
            //  下拉框
            const tempList = this.formatSpecialtyOption(res?.data?.list);
            //  账号专业
            const tempMajorCodeList = tempList.map(item => item.value);
            //  必传参数
            const tempExtraArgs = {
              majorCodeList: tempMajorCodeList,
              ...i
            }
            this.setState({
              specialtyOption: tempList,
              extraArgs: tempExtraArgs,
            }, () => {
              dispatch({
                type: 'knowledgeApply/postFetchPage',
                payload: {
                  url: '/mscontent/knowledge/apply/list',
                  ...tempExtraArgs
                }
              });
            })
          }
        }
      })
    }
  }

  //  查看故障
  handleViewBreakdown = (record: any) => {
    this.setState({
      currentRecord: record,
      visible: true,
      modalType: 'edit',
    })
  }


  //  驳回理由 modal
  showInfoModal = (txt: any) => {
    Modal.info({
      title: '驳回理由',
      content: (
        <div>
          <p>{txt}</p>
        </div>
      ),
      okText: '确认',
      onOk() {},
    });
  };

  //  查看驳回理由
   viewReject = (record: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'knowledgeApply/getDataWithRes',
      payload: { 
        url: '/mscontent/knowledge/apply/findApply',
        id: record.id,
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          this.showInfoModal(res?.data?.rejectReason);
        }
      }
    })
  }

  //  提交申请
  handleCommit = (record: any) => {
    this.changeApply(record.id, 2);
  }

  //  撤销申请
  handleBackout = (record: any) => {
    this.changeApply(record.id, 0);
  }

  changeApply = (id: number, v: number) => {
    const { dispatch } = this.props;
    const { userAccount, userId } = this.state;
    dispatch({
      type: 'http/putObj',
      payload: {
        url: '/mscontent/knowledge/apply/edit',
        id: id,
        userId,
        userAccount,
        status: v,
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          message.success('操作成功');
          this.refreshPage();
        }
      }
    })
  }

  //  删除
  handleDel = (record: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'knowledgeApply/delData',
      payload: { 
        url: `/mscontent/knowledge/apply/delete?id=${record.id}`,
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          this.refreshPage();
        }
      }
    });
  }

  refreshPage = () => {
    const { dispatch } = this.props;
    const { formValues, extraArgs } = this.state;
    dispatch({
      type: 'knowledgeApply/postFetchPage',
      payload: {
        url: '/mscontent/knowledge/apply/list',
        ...formValues,
        ...extraArgs,
      }
    });
  }

  render() {
    const {
      knowledgeApply: {
        pageData: { 
          list, 
          pagination, 
          allCount, 
          approveRejectCount, 
          approveSuccessCount, 
          approvingCount, 
          noCommitCount,
        }
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const { formValues, visible, sortOrder, specialtyOption, extraArgs, type, modalType, currentRecord } = this.state;

    const page = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      total: pagination.total,
    }

    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (page.current - 1) * page.pageSize;
        },
      },
      {
        title: '专业编码',
        dataIndex: 'majorCode',
      },
      {
        title: '故障分类',
        dataIndex: 'faultType',
        render: (text: any, record: any) => {
          return <Button type="link" style={{ padding: 0 }} onClick={() => this.handleViewBreakdown(record)}>{text}</Button>;
        }
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        defaultSortOrder: sortOrder,
        // sortOrder: sortOrder,
        sorter: (a:any, b:any) => { 
          return a.createTime > b.createTime ? 1 : -1;
        },
      },
      {
        title: '审批人',
        dataIndex: 'approveBy',
      },
      {
        title: '审批时间',
        dataIndex: 'approveTime',
      },
      {
        title: '审批状态',
        dataIndex: 'status',
        render: (text: any, record: any) => {
          return text == '3' ? <Button type="link" onClick={() => this.viewReject(record)}>驳回</Button> : statusData[text];
        }
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 160,
        render: (text: any, record: any) => {
          const tempBtns = {
            c: {
              title: '提交',
              key: 'commit',
              auth: 'knowledgeApply_commit',
              onConfirm: () => this.handleCommit(record),
            },
            d: {
              title: '删除',
              key: 'del',
              auth: 'knowledgeApply_del',
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDel(record),
            },
            w: {
              title: '撤回',
              key: 'backout',
              auth: 'knowledgeApply_withdraw',
              onConfirm: () => this.handleBackout(record),
            },
          }
          let btns: any[] = []
          if (record.status == 0 || record.status == 3) {
            //  待提交、驳回
            btns.push(tempBtns.c, tempBtns.d);
          } else if (record.status == 2) {
            //  审批中
            btns.push(tempBtns.w);
          }
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        }
      }
    ]

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => (
        <span>共&nbsp;{page === undefined ? 0 : page.total}&nbsp;条</span>
      ),
    };

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      size: "small",
      scroll: { x: 'max-content' },
      /* onChange: (pagination: any, filters: any, sorter: any, extra: any) => {
      } */
    };

    const searchItems = [
      {
        title: '专业',
        type: 'select',
        key: 'majorCode',
        selectOptions: specialtyOption || [],
      },
      {
        type: 'input',
        title: '故障分类',
        key: 'faultType',
      },
    ]
    
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: 'knowledgeApply/postFetchPage', url: '/mscontent/knowledge/apply/list' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            extraArgs={extraArgs}
            handleFormReset={() => {
              const { extraArgs: {status, ...i}} = this.state;
              this.setState({ 
                extraArgs: {
                  status: ['0', '1','2','3'],
                  ...i,
                },
                formValues: {},
                type: '1',
               })
            }}
          />
        </Card>
        <Card className={styles.standardTable}>
          {/* <Table {...tableProps} /> */}
          <div>
            <Row gutter={24}>
              <Col span={4}>
              <Button onClick={() => { this.applyKnowledge() }}>新增</Button>
              </Col>
              <Col span={20} style={{ textAlign: 'right', marginBottom: '12px' }}>
                <Radio.Group
                  onChange={({target: { value }}) => {
                    this.onChange(value)
                  }}
                  value={type}
                  optionType="button"
                  buttonStyle="solid"
                >
                  <Radio.Button value="1">全部({allCount})</Radio.Button>
                  <Radio.Button value="2">待提交({noCommitCount})</Radio.Button>
                  <Radio.Button value="3">审批中({approvingCount})</Radio.Button>
                  <Radio.Button value="4">审批通过({approveSuccessCount})</Radio.Button>
                  <Radio.Button value="5">审批驳回({approveRejectCount})</Radio.Button>
                </Radio.Group>
              </Col>
            </Row>
          </div>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'knowledgeApply/postFetchPage', url: '/mscontent/knowledge/apply/list', extraArgs: { ...extraArgs } }}
            formValues={formValues}
          />
        </Card>
        <ApplyModal
          onRef={(modalRef: any) => (this.applyModal = modalRef)}
          modalVisible={visible}
          type={modalType}
          record={currentRecord}
          specialtyOption={specialtyOption}
          closeModal={this.closeModal}
        />
      </div>
    )
  }
}
export default connect(mapStateToProps)(Apply);
